var express = require('express');
var bodyParser = require('body-parser');//解析前端传过来的数据的中间件
const jsonParser = bodyParser.json();//JSON解析器，根据具体传输的数据格式选择，比如还有：
var router = express.Router();
var fs = require('fs'); // 载入fs模块
 
/**
 * method: 
 * description: 创建xml
 * @date     
 * @author   
 */
var createXml = (fileName, txt, thenFun) => {
  
}

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title:  req.query});
});

/* GET home page. */
router.get('/download', jsonParser, function(req, res, next) {
  let fileName = req.query.fileName;
  let fileType = req.query.fileType;
  res.download("./public/xml/"+fileName+"."+fileType)
});

//同时接收get和post请求
router.post("/creatXml", jsonParser, function(req, res){
  let fileType = req.body.fileType;
  let fileName = req.body.fileName;
  let xmlValue = `${req.body.outerHTML}`;
  fs.writeFile(`./public/xml/${fileName}.${fileType}`, xmlValue.toString(), (error) => {
    if (error) {
      res.json({
        url: `./xml/${fileName}.${fileType}`,
        status: 200
      });
    } else {
      res.json({
        url: `./xml/${fileName}.${fileType}`,
        status: 100
      });
    }
  })
})

module.exports = router;
